package com.glory.dmegcpda.viewmodel

import android.os.Bundle
import androidx.databinding.ObservableArrayList
import com.glory.dmegcpda.BR
import com.glory.dmegcpda.R
import com.glory.dmegcpda.bean.CheckListEntity
import com.glory.dmegcpda.model.CheckRepository
import com.glory.mvvmnet.base.BaseViewModel
import com.glory.mvvmnet.entity.CallObserveBean
import com.glory.mvvmnet.entity.ToastMessageBean
import com.google.gson.JsonObject
import me.tatarka.bindingcollectionadapter2.ItemBinding
import java.text.SimpleDateFormat
import java.util.*

/**
 * FileName: CheckTaskListViewModel
 * Author: XJH
 * Date: 2021/10/21 11:38
 * Description:
 * History:
 */
class CheckTaskListViewModel : BaseViewModel() {
    val checkListTitle = arrayListOf(
        "序号",
        "设备类型",
        "设备编号",
        "点检表单名称",
        "状态",
        "上次点检时间",
        "即将点检时间",
        "距离时间(H)"
    )

    val checkRepository by lazy { CheckRepository() }

    val eqpType = arrayListOf<String>()

    private val onCheckTaskClick: OnClickListener = object : OnClickListener {
        override fun onChildClick(item: Any) {
            val entity = item as CheckListEntity.DataListEntity
            val bundle = Bundle()
            bundle.putString("SHEETRRN", entity.FORMRRN.toString())
            bundle.putString("OBJECTRRN", entity.OBJECTRRN.toString())
            bundle.putString("EQPID", entity.EQUIPMENTID)
            if (entity.STATUS == "FORM" || entity.STATUS == "START") {
                defUI.startActivity.value = bundle
            } else {
                val map = JsonObject()
                map.addProperty("ACTIONTYPE", "START")
                map.addProperty("SCHEDULERRN", entity.OBJECTRRN.toString())
                map.addProperty("SCHEDULETIME", entity.SCHEDULETIME)
                launchOnlyResult({
                    checkRepository.startCheck(map)
                    defUI.callObserve.value = CallObserveBean(200,0)
                })
            }
        }

    }

    //order 批次列表
    var checkItems = ObservableArrayList<CheckListEntity.DataListEntity>()
    var checkBinding =
        ItemBinding.of<CheckListEntity.DataListEntity>(
            BR.checkTaskItem,
            R.layout.item_check_task_list
        )
            .bindExtra(BR.checkTaskClick, onCheckTaskClick)


    fun searchCheckList(eqp: String, eqpType: String, formName: String, time: String) {
        checkItems.clear()
        val map = JsonObject()
        map.addProperty("ENTITYMODEL", "com.glory.pms.check.model.DailyCheckSchedule")
        var whereClause = StringBuffer()
        whereClause.append("")
        if (eqp.isNotEmpty()){
            whereClause.append("equipmentId='$eqp'")
        }
        if (eqpType.isNotEmpty()){
            if (whereClause.toString().isEmpty()){
                whereClause.append("equipmentType ='$eqpType'")
            }else{
                whereClause.append(" AND equipmentType ='$eqpType'")
            }
        }
        if (formName.isNotEmpty()){
            if (whereClause.toString().isEmpty()){
                whereClause.append("sheetName ='$eqpType'")
            }else{
                whereClause.append(" AND sheetName ='$formName'")
            }
        }
        map.addProperty("WHERECLAUSE", whereClause.toString())
        launchOnlyResult({
            val checkList = checkRepository.getCheckList(map)
            if (checkList.DATALIST.isEmpty()) {
                defUI.toastEvent.value = ToastMessageBean("服务器未返回数据", false)
                return@launchOnlyResult
            }

            checkList.DATALIST.forEach {
                it.CHECKTIME = addDate(it.COMPLETETIME,it.SCHEDULETIME)
                it.TIMEDIFFERENCE = calculateTimeDifference(it.CHECKTIME)
                it.POSITION = checkList.DATALIST.indexOf(it) + 1
            }
            if (time.isEmpty()) {
                checkItems.addAll(checkList.DATALIST)
            } else {
                checkList.DATALIST.forEach {
                    if (it.TIMEDIFFERENCE.toInt() == time.toInt()) {
                        checkItems.add(it)
                    }
                }
            }
        })


    }

    private fun addDate(date : String,defaultDate : String) : String{
        if (date.isEmpty()){
            return defaultDate
        }
        val format = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") //24小时制
        val parse = format.parse(date)
        val instance = Calendar.getInstance()
        instance.time = parse
        instance.add(Calendar.HOUR_OF_DAY,12)
        return format.format(instance.time)
    }

    private fun calculateTimeDifference(date : String) : String{
        if (date.isEmpty()){
            return "0"
        }
        val format = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") //24小时制
        val fromDate = Date()
        val toDate = format.parse(date);
        val from2 = fromDate.time;
        val to2 = toDate.time;
        val hours = ((from2 - to2) / (1000 * 60 * 60))
        return hours.toString()
    }


    fun getEqpType() {
        val map = JsonObject()
        map.addProperty("ACTIONTYPE", "GETBYREFNAME")
        map.addProperty("REFNAME", "EquipmentTypeDC")
        launchOnlyResult({
            val entity = checkRepository.getEqpType(map)
            entity.ADUREFLIST.forEach {
                eqpType.add(it.KEYID)
            }
        })
    }


    interface OnClickListener {
        fun onChildClick(item: Any)
    }

}